﻿using DAL;
using Entity.Enums;
using Entity.Models.Entities;
using Entity.Models.vo;
using IBLL;
using IDAL;
using Microsoft.AspNetCore.Http;
using RepositorySys.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using utils;
using utils.enums;
using utils.EX;
using Utils;
using Utils.enums;

namespace BLL
{
    /// <summary>
    /// 用户管理业务层
    /// </summary>
    public class UserBLL: IUserBLL
    {
        IUserDAL userDAL;
        IDepartmentBLL _departmentBLL;
        IFileInfoDAL _fileInfoDAL;
        IConsumableInfoDAL _consumableInfoDal;

        /// <summary>
        /// 数据库上下文
        /// </summary>
        RepositorySysContext _dbsysContext;
        public UserBLL(IUserDAL userDAL, IDepartmentBLL department, IFileInfoDAL fileInfoDAL, RepositorySysContext dbsysContext)
        {
            this.userDAL = userDAL;
            this._departmentBLL = department;
            this._fileInfoDAL = fileInfoDAL;
            _dbsysContext = dbsysContext;
        }

        /// <summary>
        /// 用户列表、搜索
        /// </summary>
        /// <returns></returns>
        public List<UserInfoDTO> userShow(string userName,string page,string limit,out int cont)
        {
            IQueryable<UserInfo> search = userDAL.getUserShowDAL().Where(d => d.IsDelete != true);
            if (!string.IsNullOrEmpty(userName))
            {
                search = search.Where(d => d.IsDelete != true && d.UserName.Contains(userName));
            }
            
            //分页
            var page_list = search.OrderByDescending(md => md.CreateTime).Skip((int.Parse(page) - 1) * int.Parse(limit)).Take(int.Parse(limit)).ToList();
            cont = search.Count();

            List<UserInfoDTO> UserInfo = new List<UserInfoDTO>();
            foreach (var item in page_list)
            {
                //查询部门
                DepartmentInfo departments= _departmentBLL.getByDepartment(item.DepartmentId);
                UserInfo.Add(new UserInfoDTO(item, departments));
            }
            return UserInfo;
        }

        /// <summary>
        /// 添加用户信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>
        public bool AddUser(UserInfo userInfo)
        {
            userInfo.Id = Guid.NewGuid().ToString();
            userInfo.CreateTime = DateTime.Now;
            //根据账号查询用户信息
            UserInfo byuserInfo= userDAL.getUserShowDAL().FirstOrDefault(d => d.IsDelete != true && d.Account == userInfo.Account);
            if (byuserInfo== null)
            {
                if (userInfo.DepartmentId.EndsWith("0"))
                {
                    throw new MyException(((int)UserEnums.USER_STATE.DEOAR_NONULL), Enums.getDescribe(UserEnums.USER_STATE.DEOAR_NONULL));
                }
                userInfo.PassWord = MD5.md5Encrypt(userInfo.PassWord);
                if (userDAL.AddUserDAL(userInfo) < 0)
                {
                    throw new MyException(((int)UserEnums.USER_STATE.LOSE), Enums.getDescribe(UserEnums.USER_STATE.LOSE));
                }
            }
            else
            {
                 throw new MyException(((int)UserEnums.USER_STATE.RENICE), Enums.getDescribe(UserEnums.USER_STATE.RENICE));
            }
            return true;
        }


        /// <summary>
        /// 根据账号查询用户信息
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public UserInfo byUserUser(string account)
        {
            return userDAL.getUserShowDAL().FirstOrDefault(d => d.IsDelete != true && d.Account == account);
        }

        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="userIds"></param>
        /// <returns></returns>
        public bool DatateUsers(List<string> userIds)
        {
            if (userIds.Count>0)
            {
                foreach (var item in userIds)
                {
                    DatateUser(item);
                }
            }
            else
            {
                throw new MyException(((int)UserEnums.USER_STATE.UPDATE_LIST), Enums.getDescribe(UserEnums.USER_STATE.UPDATE_LIST));

            }
            return true;
        }

        /// <summary>
        /// 删除用户信息
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public bool DatateUser(string userId)
        {
            if (userDAL.DatateUserDAL(userId) < 0)
            {
                throw new MyException(((int)UserEnums.USER_STATE.DATATE_LOSE), Enums.getDescribe(UserEnums.USER_STATE.DATATE_LOSE));

            }
            return true;
        }

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public bool UpdateUser(UserInfo user)
        {
            var entity = userDAL.getUserShowDAL().FirstOrDefault(u => u.Id == user.Id);
            entity.UserName = user.UserName;
            entity.Account = user.Account==null ? entity.Account: user.Account;
            entity.Sex = user.Sex;
            entity.PhoneNum = user.PhoneNum;
            entity.Email = user.Email;
            entity.DepartmentId = user.DepartmentId == null ? entity.DepartmentId: user.DepartmentId;
            //判断是否成功
            if (userDAL.UpdateUserDAL(entity) < 0)
            {
                throw new MyException(((int)UserEnums.USER_STATE.UPDATE_LOSE), Enums.getDescribe(UserEnums.USER_STATE.UPDATE_LOSE));
            }
            return true;
        }

        /// <summary>
        /// 获取全部主管信息
        /// </summary>
        /// <returns></returns>
        public object getLeader(string departmentid)
        {
            return  userDAL.getUserShowDAL().Where(u => u.IsDelete != true && u.Id!= departmentid).Select(u => new
            {
                u.Id,
                u.UserName
            });
        }


        /// <summary>
        /// 根据id查询用户信息
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public UserInfoVo getbyUserId(string userid)
        {
            //获取用户信息
            UserInfoVo userInfoVo= userDAL.getUserShowDAL().Where(u => u.IsDelete != true && u.Id.EndsWith(userid)).Select(u=> new UserInfoVo(u)).FirstOrDefault();
            if (userInfoVo==null)
            {
                throw new MyException(604,"找不到用户信息");
            }
            //获取用户下文件信息
            var fileInfo = _fileInfoDAL.getEntitys().Where(f => f.RelationId.EndsWith(userInfoVo.Id)).OrderByDescending(f=>f.CreateTime).ToList();
            if (fileInfo.Count>0)
            {
                userInfoVo._avatar = FileHelper.PhotoUrl(fileInfo.First().NewFileName);
            }

            return userInfoVo;
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="old_password">旧密码</param>
        /// <param name="new_password">新密码</param>
        /// <param name="again_password">确定密码</param>
        /// <returns></returns>
        public bool UpdataPassword(string old_password, string new_password, string again_password,string userid)
        {
            UserInfo userInfo = userDAL.getUserShowDAL().FirstOrDefault(u=>u.Id.EndsWith(userid));

            if (Verify(old_password, new_password, again_password, userInfo))
            {
                userInfo.PassWord = MD5.md5Encrypt(again_password);
                if (userDAL.UpdateUserDAL(userInfo) > 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 修改密码验证信息
        /// </summary>
        /// <param name="old_password"></param>
        /// <param name="new_password"></param>
        /// <param name="again_password"></param>
        /// <param name="userInfo"></param>
        private static bool Verify(string old_password, string new_password, string again_password, UserInfo userInfo)
        {
            if (userInfo != null)
            {
                //判断再次输入的密码是否一致
                if (!new_password.EndsWith(again_password))
                {
                    throw new MyException(((int)UserEnums.USER_STATE.UPDATE_PWD), Enums.getDescribe(UserEnums.USER_STATE.UPDATE_PWD));
                }
                string _Pwd = MD5.md5Encrypt(old_password);
                //判断旧密码是否正确
                if (!userInfo.PassWord.EndsWith(_Pwd))
                {
                    throw new MyException(((int)LoginEnums.REGITER_STATES.NO_ACCORD), Enums.getDescribe(LoginEnums.REGITER_STATES.NO_ACCORD));
                }
            }
            else
            {
                throw new MyException(((int)LoginEnums.REGITER_STATES.ANEW), Enums.getDescribe(LoginEnums.REGITER_STATES.ANEW));
            }
            return true;
        }

        /// <summary>
        /// 上传头像
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public string UploadAvatar(string userId, IFormFile file)
        {
            //打开事务
            using (var Transaction = _dbsysContext.Database.BeginTransaction())
            {
                //获取文件名
                string fileName = Path.GetFileName(file.FileName);
                //获得文件扩展名
                string fileNameEx = Path.GetExtension(fileName);
                //获取文件大小
                long filesz = ((long)(file.Length / 1024.0));
                //新文件名
                string newFileName = FileHelper.PhotoSave(fileNameEx);

                //上传到啊里云服务器
                if (string.IsNullOrEmpty(FileHelper.UpToAliYunImgage(file, fileNameEx, newFileName)))
                {
                    Transaction.Rollback();
                    throw new MyException(502, "上传服务器失败");
                }
                //保存到数据库
                if (_fileInfoDAL.AddEntity(new Entity.Models.Entities.FileInfo(userId, fileName, newFileName, fileNameEx, filesz, userId, FileInfoTypeEnums.PICTURE)) < 1)
                {
                    Transaction.Rollback();
                    throw new MyException(505, "保存失败");
                }
                Transaction.Commit();
                return FileHelper.PhotoUrl(newFileName);
            }
        }

        /// <summary>
        ///获取用户信息(头像)
        /// </summary>
        /// <returns></returns>
        public object getUserIcon(string userId)
        {
            //获取当前登录人信息
            UserInfo userInfo= userDAL.getUserShowDAL().FirstOrDefault(u => u.Id.EndsWith(userId));
            //获取头像文件名
            string NewFileName= _fileInfoDAL.getEntitys().OrderByDescending(f => f.CreateTime).Where(f=>f.RelationId.EndsWith(userInfo.Id)).Select(f => f.NewFileName).FirstOrDefault();
            string fileurl= FileHelper.PhotoUrl(NewFileName);
            return new { userInfo .UserName, fileurl };
        }
    }
}
